package m4;

import com.rabbitmq.client.*;
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.io.IOException;
import java.util.Scanner;


public class Consumer {
    public static void main(String[] args) throws Exception{

        /*连接*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.64.140");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        /*创建随机队列, 由服务器自动提供队列参数: 随机命名, false, true, true*/
        String queue = channel.queueDeclare().getQueue();

        /*创建交换机*/
        channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

        /*绑定, 设置关键词*/
        System.out.println("输入绑定键, 用空格隔开: ");
        String k = new Scanner(System.in).nextLine();
        String[] keys = k.split("\\s+");// \s是空白字符
        for (String key : keys) {
            channel.queueBind(queue, "direct_logs", key);
        }

        /*收到消息后,用来处理消息的回调对象*/
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到: "+s);

                System.out.println("关键词: "+message.getEnvelope().getRoutingKey());
            }
        };

        /*消费者取消时的回调对象*/
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };

        /*从队列接收消息*/
        channel.basicConsume(queue, false, deliverCallback, cancelCallback);
    }
}
